<template>
  <div class="container" v-if="createAuth">
    <!-- 头部 -->
    <page-header
      :title="
        ruleForm.id ? $t('m.Edit_role') : $t('m.jurisdiction_create_role')
      "
    >
    </page-header>
    <div class="detail_div">
      <div class="detail_left">
        <div class="detail_left_div">
          <el-form ref="ruleForm" :model="ruleForm" :rules="rules">
            <el-form-item prop="roleName">
              <div class="create_title2">
                {{ $t('m.jurisdiction_Role_name') }}*
              </div>
              <el-input
                clearable
                maxlength="50"
                :placeholder="$t('m.Please_enter')"
                v-model="ruleForm.roleName"
              ></el-input>
            </el-form-item>
            <el-form-item prop="roleDesc">
              <div class="create_title2">
                {{ $t('m.jurisdiction_Role_description') }}*
              </div>
              <div class="role_name_input">
                <el-input
                  maxlength="200"
                  clearable
                  :placeholder="$t('m.Please_enter')"
                  v-model="ruleForm.roleDesc"
                ></el-input>
              </div>
            </el-form-item>
            <el-form-item prop="menuIds">
              <div style="display: flex;justify-content: space-between;">
                <div class="create_title2">
                  {{ $t('m.jurisdiction_Permission') }}*
                </div>
                <el-checkbox
                  v-model="checkAll"
                  @change="handleCheckAllChange"
                  style="margin-right:0 !important;"
                  >{{ $t('m.Allow_all_permissions') }}</el-checkbox
                >
              </div>

              <el-tree
                ref="tree"
                :data="treeData"
                v-model="ruleForm.menuIds"
                show-checkbox
                check-strictly
                node-key="id"
                :props="{ children: 'childMenu', label: treeTitle }"
                :default-expanded-keys="expandedKeys"
                :default-checked-keys="expandedKeys"
                @check="checkChange"
              >
              </el-tree>
            </el-form-item>
          </el-form>
          <div class="role_btn" @click="submit">
            {{ ruleForm.id ? $t('m.save') : $t('m.branch_Create') }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data () {
    var choomenuIds = (rule, value, callback) => {
      let concat = this.$refs.tree.getCheckedKeys()
      if (concat.length == 0 || !concat) {
        return callback(new Error(this.$t('m.Select_role_description')))
      } else {
        callback()
      }
    }
    return {
      rules: {
        roleName: [
          {
            required: true,
            message: this.$t('m.Enter_role_name'),
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true,
            message: this.$t('m.Enter_role_description'),
            trigger: 'blur'
          }
        ],
        menuIds: [
          {
            //菜单集合
            validator: choomenuIds,
            trigger: 'change',
            required: true
          }
        ]
      },
      ruleForm: {
        roleName: '', //角色名称
        roleDesc: '', //角色描述
        menuIds: [] //菜单集合
      },

      treeData: [],
      expandedKeys: [],
      checkAll: false, //全选权限
      levelData: [],
      createAuth: this.permissionsId(160)
    }
  },
  created () {
    if (!this.createAuth) {
      return
    }
    this.getTree()
  },
  methods: {
    //全选/取消全选
    handleCheckAllChange () {
      if (this.checkAll) {
        this.$refs.tree.setCheckedNodes(this.levelData)
      } else {
        this.$refs.tree.setCheckedKeys([])
      }
    },
    // 递归调用
    recursion (arr) {
      return [].concat(
        ...arr.map(item => {
          if (item.childMenu) {
            let arr = [].concat(item, ...this.recursion(item.childMenu))
            delete item.childMenu
            return arr
          }
          return [].concat(item)
        })
      )
    },
    allFalse (list) {
      return list.every(item => item === false)
    },

    checkChange (data) {
      const node = this.$refs.tree.getNode(data.id)
      let allNodes = this.getAllNodes(this.treeData)
      allNodes.length == this.$refs.tree.getCheckedKeys().concat().length
        ? (this.checkAll = true)
        : (this.checkAll = false)
      this.setNode(node)
    },

    setNode (node) {
      // console.log(node, 'node')
      if (node.checked) {
        //如果当前是选中checkbox,则递归设置父节点和父父节点++选中
        this.setParentNode(node)
      } else {
        //当前是取消选中,将所有子节点都取消选中
        this.setChildenNode(node)
      }

      //点击选中一级的处理
      if (node.level == 1 && node.checked) {
        node.expanded = true
        let len = node.childNodes.length
        for (let i = 0; i < len; i++) {
          node.childNodes[i].expanded = true
          node.childNodes[i].checked = true
          let lens = node.childNodes[i].childNodes.length
          for (let j = 0; j < lens; j++) {
            node.childNodes[i].childNodes[j]
              ? (node.childNodes[i].childNodes[j].checked = true)
              : ''
            let lenk = node.childNodes[i].childNodes[j].childNodes.length
            for (let k = 0; k < lenk; k++) {
              node.childNodes[i].childNodes[j].childNodes[k]
                ? (node.childNodes[i].childNodes[j].childNodes[k].checked = true)
                : ''
            }
          }
        }
      }

      //点击选中二级的处理
      if (node.level == 2 && !node.checked) {
        let len = node.parent.childNodes
        let list = []
        len.forEach(item => {
          list.push(item.checked)
        })
        if (this.allFalse(list)) {
          node.parent.checked = false
        }
      }
    },

    setParentNode (node) {
      if (node.parent) {
        for (const key in node) {
          if (key === 'parent') {
            node[key].checked = true
            this.setParentNode(node[key])
          }
        }
      }
    },

    setChildenNode (node) {
      let len = node.childNodes.length
      for (let i = 0; i < len; i++) {
        node.childNodes[i].checked = false
        this.setChildenNode(node.childNodes[i])
      }
    },

    getAllNodes (node = [], arr = []) {
      for (let item of node) {
        arr.push(item.id)
        let parentArr = []
        if (item.childMenu) parentArr.push(...item.childMenu)
        if (parentArr && parentArr.length) this.getAllNodes(parentArr, arr)
      }
      return arr
    },

    getDetail () {
      this.$api.role.getDetail(this.$route.query.id).then(res => {
        if (this.$ok(res)) {
          this.ruleForm.roleName = res.data.roleName
          this.ruleForm.menuIds = res.data.menuIds
          this.ruleForm.roleDesc = res.data.roleDesc
          this.ruleForm.id = res.data.id
          this.$refs.tree.setCheckedKeys(res.data.menuIds)
          this.expandedKeys = res.data.menuIds
          let allNodes = this.getAllNodes(this.treeData)
          allNodes.length == res.data.menuIds.length
            ? (this.checkAll = true)
            : (this.checkAll = false)
        }
      })
    },

    getTree () {
      this.$api.role.getTree(this.roleName).then(res => {
        if (this.$ok(res)) {
          this.treeData = res.data.menuList
          let cloneData = JSON.parse(JSON.stringify(res.data.menuList))
          this.levelData = this.recursion(cloneData)
          if (this.$route.query.id) {
            this.ruleForm.id = this.$route.query.id
            this.getDetail()
          }
        }
      })
    },

    submit () {
      const concat = this.$refs.tree.getCheckedKeys().concat()
      if (concat.length == 0) {
        this.ruleForm.menuIds = ''
      } else {
        this.ruleForm.menuIds = concat
      }
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.$api.role.createModify(this.ruleForm).then(res => {
            if (this.$ok(res)) {
              this.$message.success(res.message)
              this.back()
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    treeTitle (data, node) {
      // console.log(data, node)
      return this.$util.langFormat(data.title)
    }
  }
}
</script>
<style scoped lang="scss">
.detail_div {
  background: #ffffff;
  border-radius: 10px !important;
  margin: 0 20px;
  .detail_left {
    background: #ffffff;
    border-radius: 10px !important;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 0 !important;
    .detail_left_div {
      padding-bottom: 36px !important;
      margin-top: 0 !important;
      .el-form {
        width: 490px;
      }
      .role_btn {
        width: 488px;
        height: 44px;
        background: $color;
        border-radius: 10px;
        color: #ffffff;
        margin-top: 44px;
        font-size: 13px;
        font-weight: 500;
        text-align: center;
        color: #ffffff;
        line-height: 44px;
        cursor: pointer;
      }
    }
  }
}

.container {
  width: 100%;
  min-width: 1000px !important;
  .page-header {
    padding: 20px 0;
  }
  .page-header,
  .detail_div {
    width: 100%;
    min-width: 1000px !important;
    max-width: 1000px !important;
  }
}

@media screen and (min-width: 1221px) {
  .container {
    display: flex;
    justify-content: center;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
  }
}
</style>
